﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using NPOI.HPSF;

namespace Matrix.MaKaYunShang.MagWeb.Filter
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
    public class PermissionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var hasRight = false;
            var controller = (string)filterContext.RouteData.Values["controller"];
            var action = (string)filterContext.RouteData.Values["action"];
            var currentAccount = HttpContext.Current.Session["user"] as MagUser;
            //检查被请求的方法和控制器是\否有Skip标签,如果有,就不验证,如果没有就验证
            if (filterContext.ActionDescriptor.IsDefined(typeof(Matrix.MaKaYunShang.Model.Attributes.SkipAttribute), false) &&
                filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(Matrix.MaKaYunShang.Model.Attributes.SkipAttribute), false))
            {
                hasRight = true;
            }
            else
            {

                var allowedModules = GetAllowedModules(currentAccount);
                allowedModules.RemoveAll(s => s == null);
                if (currentAccount != null && currentAccount.RoleId != 1)
                {


                    allowedModules = allowedModules.Where(t => t
                        .Action.Equals(action) && t
                            .Controller.Equals(controller)).ToList();
                    if (allowedModules.Count > 0)
                    {
                        hasRight = true;

                    }
                }
                else
                {
                    // 如果是超级用户 直接返回 获取所有操作权限
                    hasRight = true;
                }
            }
            if (hasRight)
                return;
            filterContext.HttpContext.Response.Write(
          "<script type='text/javascript'>alert('无访问权限，请联系您的上级管理员！'); location.href = '/Home/Index';</script>");
            filterContext.Result = new EmptyResult();
        }


        //public override void OnActionExecuting(ActionExecutingContext filterContext)
        //{
        //    var hasRight = false;
        //    var controller = (string)filterContext.RouteData.Values["controller"];
        //    var action = (string)filterContext.RouteData.Values["action"];
        //    var currentAccount = HttpContext.Current.Session["user"] as MagUser;
        //    if (controller == "Login" || controller == "Home")
        //    {
        //        hasRight = true;
        //    }
        //    else
        //    {

        //        var allowedModules = GetAllowedModules(currentAccount);

        //        if (currentAccount != null && allowedModules != null && currentAccount.RoleId != 1)
        //        {
        //            if (allowedModules.TrueForAll(t => t
        //                    .Action == action && t
        //                    .Controller == controller))
        //            {
        //                hasRight = true;

        //            }
        //        }
        //        else
        //        {
        //            // 如果是超级用户 直接返回 获取所有操作权限
        //            hasRight = true;
        //        }
        //    }
        //    if (hasRight)
        //        return;
        //    filterContext.HttpContext.Response.Write(
        //        "<script type='text/javascript'>alert('无访问权限，请联系您的上级管理员！'); location.href = '/Home/Index';</script>");
        //    filterContext.Result = new EmptyResult();
        //}

        /// <summary>
        ///     获取当前用户所有有权限执行的动作
        /// </summary>
        /// <returns></returns>
        private List<MagModules> GetAllowedModules(MagUser user)
        {
            var lsModuleIds =
                MagRoleModulePermissionBLL.Instance.GetModelListByRoleId(user.RoleId).Select(x => x.ModuleId).ToList();

            return lsModuleIds.Select(moduleId => MagModulesBLL.Instance.GetModel(moduleId)).ToList();
        }
    }
}